<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="教育集团名称" prop="edgroup_id">
        <el-select
          v-model="queryParams.edgroup_id"
          style="width: 200px"
          :filterable="true"
          :clearable="true"
          @change="changeEdgroup"
          :disabled="edgroup_id"
        >
          <el-option
            v-for="item in EdgroupList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="学校名称"
        prop="school_id"
        v-if="queryParams.edgroup_id"
      >
        <el-select
          v-model="queryParams.school_id"
          style="width: 200px"
          :filterable="true"
          :clearable="true"
          @change="changeSchool"
          :disabled="school_id"
        >
          <el-option
            v-for="item in schoolList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="班级名称"
        prop="class_id"
        v-if="queryParams.school_id"
      >
        <el-select
          v-model="queryParams.class_id"
          style="width: 200px"
          :filterable="true"
          :clearable="true"
          :disabled="class_id"
        >
          <el-option
            v-for="item in classList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学生名称" prop="name">
        <el-input
          v-model="queryParams.name"
          class="icon-search"
          clearable
          placeholder="请输入学生名称"
          @keyup.enter="handleQuery"
        >
          <template #suffix
            ><i class="el-icon-search el-input__icon"
          /></template>
        </el-input>
      </el-form-item>
      <el-form-item label="手环名称" prop="fw_name">
        <el-input
          v-model="queryParams.fw_name"
          placeholder="请输入手环名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="MAC地址" prop="mac">
        <el-input
          v-model="queryParams.mac"
          placeholder="请输入MAC地址"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="固件版本" prop="fw_version">
        <el-input
          v-model="queryParams.fw_version"
          placeholder="请输入固件版本"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="OTA任务编号" prop="task_id">
        <el-input
          v-model="queryParams.task_id"
          placeholder="请输入任务编号"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="创建时间" style="width: 308px">
            <el-date-picker
               v-model="dateRange"
               value-format="YYYY-MM-DD"
               type="daterange"
               range-separator="-"
               start-placeholder="开始日期"
               end-placeholder="结束日期"
            ></el-date-picker>
         </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:post:add']"
          >新增OTA任务</el-button
        >
      </el-col> -->
      <!--<el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="creatOTA"
          v-hasPermi="['system:post:add']"
          >创建OTA任务</el-button
        >
      </el-col>-->
      <!-- <el-col :span="1.5">
            <el-button
               type="success"
               plain
               icon="Edit"
               :disabled="single"
               @click="handleUpdate"
               v-hasPermi="['system:post:edit']"
            >修改</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button
               type="danger"
               plain
               icon="Delete"
               :disabled="multiple"
               @click="handleDelete"
               v-hasPermi="['system:post:remove']"
            >删除</el-button>
         </el-col>
          -->
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExportWB">导出手环数据</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          >导出手环(5分钟内)</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain @click="creatOTA">触发OTA</el-button>
      </el-col>
      <!-- 当选择查询条件有 class_id 的时候 -->
      <el-col :span="1.5" v-if="class_id">
        <el-button type="danger" plain @click="creatAllOTA">全部OTA</el-button>
      </el-col>
      <right-toolbar
        :showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="wristbandList"
      size="small"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" width="60" type="index" align="center">
        <template #default="scope">
          <span>{{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="手环编号" prop="id" align="center" show-overflow-tooltip/> -->
      <el-table-column label="MAC地址" width="150" align="center" prop="mac" />
      <el-table-column
        label="教育集团名称 / 学校名称 / 班级名称"
        min-width="330"
        align="center"
        prop="student_wristband"
      >
        <template #default="scope">
          <el-tag
            v-if="
              scope.row.student_wristband?.student?.class?.school?.edgroup?.name
            "
            type="danger"
          >
            {{
              scope.row.student_wristband?.student?.class?.school?.edgroup?.name
            }}
          </el-tag>
          <el-tag
            v-if="scope.row.student_wristband?.student?.class?.school?.name"
            type="primary"
          >
            {{ scope.row.student_wristband?.student?.class?.school?.name }}
          </el-tag>
          <el-tag
            v-if="scope.row.student_wristband?.student?.class?.name"
            type="warning"
          >
            {{ scope.row.student_wristband?.student?.class?.name }}
          </el-tag>
          <!-- <el-tag v-if="scope.row.student_wristband?.student?.name" type="info">
            {{
              scope.row.student_wristband?.student?.name.length > 2
                ? scope.row.student_wristband?.student?.name[0] +
                  "*" +
                  scope.row.student_wristband?.student?.name.slice(-1)
                : scope.row.student_wristband?.student?.name[0] + "*"
            }}
          </el-tag> -->
        </template>
        <!-- <template #default="scope">
          {{ [scope.row.student_wristband?.student?.class?.school?.edgroup?.name,
          scope.row.student_wristband?.student?.class?.school?.name,
          scope.row.student_wristband?.student?.class?.name,
          scope.row.student_wristband?.student?.name].map(item => item || '未知').join(' / ') }}
        </template> -->
      </el-table-column>
      <el-table-column
        label="学号"
        min-width="330"
        align="center"
        prop="student_wristband.student.s_number"
        sortable
        :sort-by="
          (row) => Number(row.student_wristband?.student?.s_number) || 0
        "
      />
      <el-table-column
        label="学生"
        min-width="330"
        align="center"
        sortable
        prop="student_wristband"
      >
        <template #default="scope">
          <el-tag v-if="scope.row.student_wristband?.student?.name" type="info">
            {{
              scope.row.student_wristband?.student?.name.length > 2
                ? scope.row.student_wristband?.student?.name[0] +
                  "*" +
                  scope.row.student_wristband?.student?.name.slice(-1)
                : scope.row.student_wristband?.student?.name[0] + "*"
            }}
          </el-tag>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column
        label="手环名称"
        align="center"
        prop="fw_name"
        min-width="100"
        sortable
      />
      <el-table-column
        label="固件版本"
        align="center"
        prop="fw_version"
        min-width="100"
        sortable
      >
        <template #default="scope">
          <el-tag v-if="scope.row?.fw_version" type="danger">
            {{ scope.row.fw_version }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="固件/OTA任务编号"
        align="center"
        prop="taskid"
        sortable
        min-width="200"
      >
        <template #default="scope">
          <span>{{ scope.row?.firmwareid || "--" }}</span> /
          <el-tag v-if="scope.row?.taskid" type="primary">
            {{ scope.row.taskid }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="OTA时间"
        align="center"
        prop="last_ota_time"
        min-width="200"
        sortable
        :sort-by="
          (row) =>
            row?.last_ota_time ? new Date(row?.last_ota_time).getTime() : 0
        "
      >
        <!-- :sort-method="sortTime" -->
        <template #default="scope">
          <span v-if="scope.row?.last_ota_time">
            {{ scope?.row.last_ota_time || "--" }}
            (
            <span style="color: #67c23a">{{
              formatOnlineTime(scope.row?.last_ota_time)
            }}</span>
            )
          </span>
          <span v-else> -- </span>
        </template>
      </el-table-column>
      <el-table-column
        label="在线时间"
        align="center"
        prop="online_time"
        min-width="240"
        sortable
      >
        <template #default="scope">
          <!-- {{ scope.row.time ? formartIOSDate(scope.row.time) : "--" }} -->
          <span v-if="scope.row.online_time">
            {{ formartIOSDate(scope.row.online_time) || "--" }}
            (
            <span style="color: #67c23a">{{
              formatOnlineTime(formartIOSDate(scope.row.online_time))
            }}</span>
            )
          </span>
          <span v-else> -- </span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="网关编号" width="320" align="center" prop="id" /> -->
      <el-table-column
        label="创建时间"
        align="center"
        prop="time"
        width="180"
        sortable
      >
        <template #default="scope">
          {{ scope.row.time ? formartIOSDate(scope.row.time) : "--" }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="240"
        fixed="right"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleView(scope.row)"
            >查看</el-button
          >
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleHistoryView(scope.row)"
            >历史记录</el-button
          >
          <el-button
            link
            type="primary"
            icon="Download"
            @click="handleExportWB(scope.row, '1d')"
            >导出</el-button
          >
          <el-button
            link
            type="primary"
            icon="Download"
            @click="showExportDialog(scope.row, '1d')"
            >导出统计</el-button
          >
          <!-- <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:post:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:post:remove']"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- OTA任务创建 -->

    <el-dialog
      :title="title"
      v-model="openOTA"
      width="500px"
      append-to-body
      @close="cancelOTA"
    >
      <el-form
        ref="OTARef"
        :model="formOTA"
        :rules="rulesOTA"
        label-width="120px"
        @submit.prevent
      >
        <el-form-item label="手环固件" prop="firmwareid">
          <el-select
            v-model="formOTA.firmwareid"
            placeholder="请选择手环固件"
            :loading="firmwareLoading"
            @change="(value) => firmwareChange('wb', Number(value))"
            style="width: 260px"
          >
            <el-option
              v-for="dict in firmwaresLists.wb || []"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            >
              <template v-if="!firmwareLoading && !firmwaresLists.wb?.length">
                <el-option disabled value="">暂无可用固件</el-option>
              </template>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input
            v-model="formOTA.path"
            placeholder="请输入路径"
            style="width: 260px"
          />
        </el-form-item>
        <!-- v-if="
            formOTA.firmwareType === 'gw-bin' ||
            formOTA.firmwareType === 'gw-fs'
          " -->
        <el-form-item label="网关MAC地址" prop="gw_mac">
          <el-select
            clearable
            v-model="formOTA.gw_mac"
            multiple
            filterable
            allow-create
            placeholder="请选择或输入网关"
            :multiple-limit="10"
            style="width: 260px"
            :disabled="formOTA.gw_full === 1"
          >
            <el-option
              v-for="item in gatewayList"
              :key="item.mac"
              :label="item.mac"
              :value="item.mac"
            />
          </el-select>
          <!-- <el-input v-model="formOTA.gw_mac" placeholder="请输入网关" style="width: 260px"/> -->
          &nbsp;&nbsp;&nbsp;
          <el-checkbox
            :true-label="1"
            :false-label="0"
            v-model="formOTA.gw_full"
            @change="gwFullChange($event)"
            :disabled="class_id || formOTA.isprod"
            >全部</el-checkbox
          >
        </el-form-item>
        <el-form-item label="手环MAC地址" prop="wb_mac">
          <el-select
            v-model="formOTA.wb_mac"
            multiple
            filterable
            allow-create
            placeholder="请选择或输入手环网关"
            clearable
            :multiple-limit="50"
            style="width: 260px"
            disabled
          >
            <el-option
              v-for="item in wristbandList"
              :key="item.mac"
              :label="item.mac"
              :value="item.mac"
            />
          </el-select>
          <!-- <el-input v-model="formOTA.wb_mac" placeholder="请输入手环网关" style="width: 260px"/> -->
          &nbsp;&nbsp;&nbsp;
        </el-form-item>
        <!-- <el-form-item label="强制更新" prop="wb_mac">
          <el-switch v-model="formOTA.force" @change="forceChange" />
        </el-form-item>
        <el-form-item label="长期更新" prop="wb_mac">
          <el-switch
            :disabled="!(formOTA.gw_full || formOTA.wb_full)"
            v-model="formOTA.remain"
            @change="remainChange"
          />
        </el-form-item> -->
        <!-- "uponly" | "updown" | "force", -->
        <el-form-item label="升级模式" prop="updateMode">
          <el-radio-group v-model="formOTA.updateMode" class="ml-4">
            <el-radio
              v-for="item in ota_update_mode"
              :key="item.value"
              :label="item.value"
              size="large"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
          <!-- <el-text type="danger" size="small">开启固件可升级非当前版本，反之只可升级大于当前版本。</el-text> -->
        </el-form-item>
        <el-form-item label="升级限制" prop="updateLimit">
          <el-radio-group v-model="formOTA.updateLimit" class="ml-4">
            <el-radio
              v-for="item in ota_update_limit"
              :key="item.value"
              :label="item.value"
              size="large"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="formOTA.updateLimit == 1"
          label="升级时限"
          prop="duration"
        >
          <el-input-number
            v-model="formOTA.duration"
            placeholder="请输入手环升级时长限制"
            class="mx-4"
            :min="0"
            :max="86400"
            :step="1"
            step-strictly
            controls-position="left"
            style="width: 260px"
          />
          <span>&nbsp;&nbsp;&nbsp;&nbsp;秒</span>
          <!-- <el-text type="danger" size="small">限制手环升级时长，当到达指定时长则停止升级任务。</el-text> -->
        </el-form-item>
        <el-form-item
          v-if="formOTA.updateLimit == 2"
          label="升级数量"
          prop="wb_count"
        >
          <el-input-number
            v-model="formOTA.wb_count"
            placeholder="请输入手环升级数量"
            class="mx-4"
            :min="0"
            :max="10000"
            :step="1"
            step-strictly
            controls-position="left"
            style="width: 260px"
          />
          <el-text type="danger" size="small"
            >限制手环升级数量，当指定数量升完则停止升级任务。</el-text
          >
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormOTA">确 定</el-button>
          <el-button @click="cancelOTA">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改岗位对话框 -->
    <!-- <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="wristbandRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        @submit.prevent
      >
      <el-form-item label="是否全选">
          <el-radio-group v-model="form.full" prop="full">
            <el-radio value="0">是</el-radio>
            <el-radio value="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="固件类型" prop="firmware">
          <el-select
            v-model="form.firmware"
            multiple
            allow-create
            filterable
            placeholder="请选择固件类型"
          >
            <el-option
              v-for="dict in firmware_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="固件名称" prop="name">
          <el-select
            v-model="form.firmwareid"
            multiple
            placeholder="请选择固件名称"
          >
            <el-option
              v-for="post in wristbandList"
              :key="post.id"
              :label="post.name"
              :value="post.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="网关" prop="gw_mac">
          <el-input v-model="form.gw_mac" placeholder="请输入网关" />
        </el-form-item>
        <el-form-item label="手环网关" prop="wb_mac">
          <el-input v-model="form.wb_mac" placeholder="请输入手环网关" />
        </el-form-item>
        <el-form-item label="状态" prop="action">
          <el-radio-group v-model="form.action" prop="action">
            <el-radio
              v-for="action in action_ota"
              :key="action.value"
              :value="action.value"
              >{{ action.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="value">
          <el-input v-model="form.value" placeholder="备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog> -->
    <!-- 手环详情数据 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="90%"
      append-to-body
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <el-row :gutter="20">
        <el-col :span="5" :xs="24">
          <el-card class="box-card">
            <template v-slot:header>
              <div class="clearfix">
                <span>手环信息</span>
              </div>
            </template>
            <div class="list-group-top-none">
              <ul class="list-group list-group-striped">
                <li class="list-group-item">
                  <!-- <svg-icon icon-class="cpu" /> -->
                  <el-icon class="cpu"><plus /></el-icon>MAC地址
                  <div class="pull-right">
                    {{ queryParamsDetail.current_wb.mac || "--" }}
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone" />固件版本号
                  <div class="pull-right">
                    {{ queryParamsDetail.current_wb.fw_version || "--" }}
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone" />最旧idx
                  <div class="pull-right">
                    {{ last_idx }}
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone" />最新idx
                  <div class="pull-right">
                    {{ new_idx }}
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone" />理论包数
                  <div class="pull-right">
                    {{ pack_count }}
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone" />实际接收包数
                  <div class="pull-right">
                    {{ true_pack_count }}
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone" />丢失包数
                  <div class="pull-right">
                    {{ lost_pack_count }}
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone" />丢包率
                  <div class="pull-right">{{ lost_pack_percent }}%</div>
                </li>
              </ul>
            </div>
          </el-card>
        </el-col>
        <el-col :span="19" :xs="24">
          <el-card class="wristbandDetail">
            <template v-slot:header>
              <div class="clearfix">
                <span>最近数据</span>
                <!-- 共查找到<b style="color:#F56C6C">{{ totalDetail || 0 }}</b>条 -->
              </div>
            </template>
            <el-form
              :model="queryParamsDetail"
              ref="queryDetailRef"
              :inline="true"
            >
              <!-- v-show="showSearch" -->
              <el-form-item label="网关MAC地址" prop="gw_mac">
                <el-input
                  v-model="queryParamsDetail.gw_mac"
                  placeholder="请输入网关MAC地址"
                  clearable
                  style="width: 200px"
                  @keyup.enter="handleQueryDetail"
                />
              </el-form-item>
              <el-form-item label="统计时间">
                <el-date-picker
                  v-model="queryParamsDetail.date"
                  type="datetimerange"
                  range-separator="至"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                >
                </el-date-picker>
                <!-- <el-date-picker
                      v-model="queryParamsDetail.time"
                      type="datetime"
                      placeholder="选择日期时间">
                    </el-date-picker> -->
                <!-- <el-date-picker
                      v-model="queryParamsDetail.time"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="选择日期">
                    </el-date-picker> -->
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  icon="Search"
                  @click="handleQueryDetail"
                  >搜索</el-button
                >
                <el-button icon="Refresh" @click="resetQueryDetail"
                  >重置</el-button
                >
                <el-button
                  :icon="queryParamsDetail.status ? 'VideoPause' : 'VideoPlay'"
                  @click="timedQueryDetail"
                  >{{ queryParamsDetail.status ? "暂停" : "开始" }}</el-button
                >
              </el-form-item>
            </el-form>
            <el-table
              v-loading="loadingDetail"
              :data="wristbandDetail"
              size="small"
              @selection-change="handleSelectionChange"
              max-height="800px"
            >
              <!-- <el-table-column
                label="序号"
                width="60"
                type="index"
                align="center"
              /> -->
              <el-table-column
                label="序列号"
                prop="idx"
                align="center"
                sortable
                fixed="left"
              />
              <!-- <el-table-column label="手环MAC地址" width="150" align="center" prop="mac" /> -->
              <el-table-column label="心率" align="center" prop="hr">
                <template #default="scope">
                  {{ scope.row.hr }} (
                  <b v-if="scope.row?.fake_hr" style="color: #f56c6c">1</b>
                  <b v-else style="color: #67c23a">0</b> )
                </template>
              </el-table-column>
              <el-table-column label="步数" align="center" prop="steps">
                <template #default="scope">
                  <b :style="{ color: getStepsColor(scope.row.steps) }">
                    {{ scope.row?.steps || 0 }}
                  </b>
                </template>
              </el-table-column>
              <el-table-column
                label="运动强度"
                width="80"
                align="center"
                prop="motion"
              >
                <template #default="scope">
                  <b
                    :style="{
                      color:
                        scope.row?.motion && scope.row?.motion > 0
                          ? 'inherit'
                          : '#F56C6C',
                    }"
                  >
                    {{ scope.row?.motion ? scope.row.motion.toFixed(6) : 0 }}
                  </b>
                </template>
              </el-table-column>
              <el-table-column
                label="运动强度方差"
                width="100"
                align="center"
                prop="motion_variance"
              >
                <template #default="scope">
                  <b
                    :style="{
                      color:
                        scope.row?.motion_variance &&
                        scope.row?.motion_variance > 0
                          ? 'inherit'
                          : '#F56C6C',
                    }"
                  >
                    {{
                      scope.row?.motion_variance
                        ? scope.row.motion_variance.toFixed(6)
                        : 0
                    }}
                  </b>
                </template>
              </el-table-column>
              <el-table-column label="温度" align="center" prop="temperature">
                <template #default="scope">
                  <b
                    :style="{
                      color: getTemperatureColor(scope.row?.temperature),
                    }"
                  >
                    {{ scope.row?.temperature || 0 }}
                  </b>
                </template>
              </el-table-column>
              <el-table-column label="区角豆1" align="center" prop="beacon1">
                <template #default="scope">
                  <b
                    :style="{
                      color:
                        scope.row?.beacon1 && scope.row?.beacon1 > 0
                          ? '#67c23a'
                          : '#F56C6C',
                    }"
                  >
                    {{ scope.row?.beacon1 || 0 }}
                  </b>
                </template>
              </el-table-column>
              <el-table-column label="区角豆2" align="center" prop="beacon2">
                <template #default="scope">
                  <b
                    :style="{
                      color:
                        scope.row?.beacon2 && scope.row?.beacon2 > 0
                          ? '#67c23a'
                          : '#F56C6C',
                    }"
                  >
                    {{ scope.row?.beacon2 || 0 }}
                  </b>
                </template>
              </el-table-column>
              <el-table-column label="区角豆3" align="center" prop="beacon3">
                <template #default="scope">
                  <b
                    :style="{
                      color:
                        scope.row?.beacon3 && scope.row?.beacon3 > 0
                          ? '#67c23a'
                          : '#F56C6C',
                    }"
                  >
                    {{ scope.row?.beacon3 || 0 }}
                  </b>
                </template>
              </el-table-column>
              <!-- <el-table-column label="x" align="center" prop="acc_x" />
              <el-table-column label="y" align="center" prop="acc_y" />
              <el-table-column label="z" align="center" prop="acc_z" /> -->
              <el-table-column label="信号" align="center" prop="rssi">
                <template #default="scope">
                  <b :style="{ color: getRssiColor(scope.row?.rssi || 0) }">
                    {{ scope.row?.rssi || "--" }}
                  </b>
                </template>
              </el-table-column>
              <el-table-column label="格式" align="center" prop="format" />
              <el-table-column
                label="网关MAC地址"
                width="150"
                align="center"
                prop="gw_mac"
                sortable
                fixed="right"
              />
              <el-table-column
                label="时间"
                align="center"
                prop="time"
                min-width="200"
                sortable
                fixed="right"
              >
                <template #default="scope">
                  <!-- {{ scope.row.time ? formartIOSDate(scope.row.time) : "--" }} -->
                  <span v-if="scope.row.time">
                    {{ formartIOSDate(scope.row.time) || "--" }}
                    (
                    <span style="color: #67c23a">{{
                      formatOnlineTime(formartIOSDate(scope.row.time))
                    }}</span>
                    )
                  </span>
                  <span v-else> -- </span>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                width="180"
                fixed="right"
                align="center"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    icon="Download"
                    @click="handleExportWB(scope.row, '5m')"
                    >导出</el-button
                  >
                  <el-button
                    link
                    type="primary"
                    icon="Download"
                    @click="showExportDialog(scope.row, '5m')"
                    >导出统计</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="totalDetail > 0"
              :layout="'total, sizes, prev, pager, next'"
              :total="totalDetail"
              size="small"
              v-model:page="queryParamsDetail.pageNum"
              v-model:limit="queryParamsDetail.pageSize"
              @pagination="getWristbandDetails"
              style="max-width: 100%; margin: 0 auto"
            />
          </el-card>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" @click="submitForm">确 定</el-button> -->
          <el-button @click="cancelDetail">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 手环历史详情 -->
    <el-dialog
      :title="title"
      v-model="openHistory"
      width="90%"
      append-to-body
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <el-row :gutter="20">
        <el-col :span="5" :xs="24">
          <el-card class="box-card">
            <template v-slot:header>
              <div class="clearfix">
                <span>手环历史信息</span>
              </div>
            </template>
            <div class="list-group-top-none">
              <ul class="list-group list-group-striped">
                <li class="list-group-item">
                  <!-- <svg-icon icon-class="cpu" /> -->
                  <el-icon class="cpu"><plus /></el-icon>MAC地址
                  <div class="pull-right">
                    {{ queryParamsDetail.current_wb.mac || "--" }}
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone" />固件版本号
                  <div class="pull-right">
                    {{ queryParamsDetail.current_wb.fw_version || "--" }}
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone" />最旧idx
                  <div class="pull-right">
                    {{ last_idx }}
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone" />最新idx
                  <div class="pull-right">
                    {{ new_idx }}
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone" />理论包数
                  <div class="pull-right">
                    {{ pack_count }}
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone" />实际接收包数
                  <div class="pull-right">
                    {{ true_pack_count }}
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone" />丢失包数
                  <div class="pull-right">
                    {{ lost_pack_count }}
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone" />丢包率
                  <div class="pull-right">{{ lost_pack_percent }}%</div>
                </li>
              </ul>
            </div>
          </el-card>
        </el-col>
        <el-col :span="19" :xs="24">
          <el-card class="wristbandDetail">
            <template v-slot:header>
              <div class="clearfix">
                <span>最近数据</span>
                <!-- 共查找到<b style="color:#F56C6C">{{ totalDetail || 0 }}</b>条 -->
              </div>
            </template>
            <el-form
              :model="queryParamsDetail"
              ref="queryDetailRef"
              :inline="true"
            >
              <!-- v-show="showSearch" -->
              <el-form-item label="网关MAC地址" prop="gw_mac">
                <el-input
                  v-model="queryParamsDetail.gw_mac"
                  placeholder="请输入网关MAC地址"
                  clearable
                  style="width: 200px"
                  @keyup.enter="handleQueryHistoryDetail"
                />
              </el-form-item>
              <el-form-item label="统计时间">
                <el-date-picker
                  v-model="queryParamsDetail.date"
                  type="datetimerange"
                  range-separator="至"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                >
                </el-date-picker>
                <!-- <el-date-picker
                      v-model="queryParamsDetail.time"
                      type="datetime"
                      placeholder="选择日期时间">
                    </el-date-picker> -->
                <!-- <el-date-picker
                      v-model="queryParamsDetail.time"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="选择日期">
                    </el-date-picker> -->
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  icon="Search"
                  @click="handleQueryHistoryDetail"
                  >搜索</el-button
                >
                <el-button icon="Refresh" @click="resetQueryHistoryDetail"
                  >重置</el-button
                >
              </el-form-item>
            </el-form>
            <el-table
              v-loading="loadingDetail"
              :data="wristbandDetail"
              size="small"
              @selection-change="handleSelectionChange"
              max-height="800px"
            >
              <!-- <el-table-column
                label="序号"
                width="60"
                type="index"
                align="center"
              /> -->
              <el-table-column
                label="序列号"
                prop="idx"
                align="center"
                sortable
                fixed="left"
              />
              <!-- <el-table-column label="手环MAC地址" width="150" align="center" prop="mac" /> -->
              <el-table-column label="心率" align="center" prop="hr">
                <template #default="scope">
                  {{ scope.row.hr }} (
                  <b v-if="scope.row?.fake_hr" style="color: #f56c6c">1</b>
                  <b v-else style="color: #67c23a">0</b> )
                </template>
              </el-table-column>
              <el-table-column label="步数" align="center" prop="steps">
                <template #default="scope">
                  <b :style="{ color: getStepsColor(scope.row.steps) }">
                    {{ scope.row?.steps || 0 }}
                  </b>
                </template>
              </el-table-column>
              <el-table-column
                label="运动强度"
                width="80"
                align="center"
                prop="motion"
              >
                <template #default="scope">
                  <b
                    :style="{
                      color:
                        scope.row?.motion && scope.row?.motion > 0
                          ? 'inherit'
                          : '#F56C6C',
                    }"
                  >
                    {{ scope.row?.motion ? scope.row.motion.toFixed(6) : 0 }}
                  </b>
                </template>
              </el-table-column>
              <el-table-column
                label="运动强度方差"
                width="100"
                align="center"
                prop="motion_variance"
              >
                <template #default="scope">
                  <b
                    :style="{
                      color:
                        scope.row?.motion_variance &&
                        scope.row?.motion_variance > 0
                          ? 'inherit'
                          : '#F56C6C',
                    }"
                  >
                    {{
                      scope.row?.motion_variance
                        ? scope.row.motion_variance.toFixed(6)
                        : 0
                    }}
                  </b>
                </template>
              </el-table-column>
              <el-table-column label="温度" align="center" prop="temperature">
                <template #default="scope">
                  <b
                    :style="{
                      color: getTemperatureColor(scope.row?.temperature),
                    }"
                  >
                    {{ scope.row?.temperature || 0 }}
                  </b>
                </template>
              </el-table-column>
              <el-table-column label="区角豆1" align="center" prop="beacon1">
                <template #default="scope">
                  <b
                    :style="{
                      color:
                        scope.row?.beacon1 && scope.row?.beacon1 > 0
                          ? '#67c23a'
                          : '#F56C6C',
                    }"
                  >
                    {{ scope.row?.beacon1 || 0 }}
                  </b>
                </template>
              </el-table-column>
              <el-table-column label="区角豆2" align="center" prop="beacon2">
                <template #default="scope">
                  <b
                    :style="{
                      color:
                        scope.row?.beacon2 && scope.row?.beacon2 > 0
                          ? '#67c23a'
                          : '#F56C6C',
                    }"
                  >
                    {{ scope.row?.beacon2 || 0 }}
                  </b>
                </template>
              </el-table-column>
              <el-table-column label="区角豆3" align="center" prop="beacon3">
                <template #default="scope">
                  <b
                    :style="{
                      color:
                        scope.row?.beacon3 && scope.row?.beacon3 > 0
                          ? '#67c23a'
                          : '#F56C6C',
                    }"
                  >
                    {{ scope.row?.beacon3 || 0 }}
                  </b>
                </template>
              </el-table-column>
              <!-- <el-table-column label="x" align="center" prop="acc_x" />
              <el-table-column label="y" align="center" prop="acc_y" />
              <el-table-column label="z" align="center" prop="acc_z" /> -->
              <el-table-column label="信号" align="center" prop="rssi">
                <template #default="scope">
                  <b :style="{ color: getRssiColor(scope.row?.rssi || 0) }">
                    {{ scope.row?.rssi || "--" }}
                  </b>
                </template>
              </el-table-column>
              <el-table-column label="格式" align="center" prop="format" />
              <el-table-column
                label="网关MAC地址"
                width="150"
                align="center"
                prop="gw_mac"
                sortable
                fixed="right"
              />
              <el-table-column
                label="时间"
                align="center"
                prop="time"
                min-width="200"
                sortable
                fixed="right"
              >
                <template #default="scope">
                  <!-- {{ scope.row.time ? formartIOSDate(scope.row.time) : "--" }} -->
                  <span v-if="scope.row.time">
                    {{ formartIOSDate(scope.row.time) || "--" }}
                    (
                    <span style="color: #67c23a">{{
                      formatOnlineTime(formartIOSDate(scope.row.time))
                    }}</span>
                    )
                  </span>
                  <span v-else> -- </span>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                width="180"
                fixed="right"
                align="center"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    icon="Download"
                    @click="handleExportWB(scope.row, '5m')"
                    >导出</el-button
                  >
                  <el-button
                    link
                    type="primary"
                    icon="Download"
                    @click="showExportDialog(scope.row, '5m')"
                    >导出统计</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="totalDetail > 0"
              :layout="'total, sizes, prev, pager, next'"
              :total="totalDetail"
              size="small"
              v-model:page="queryParamsDetail.pageNum"
              v-model:limit="queryParamsDetail.pageSize"
              @pagination="getWristbandHistoryDetails"
              style="max-width: 100%; margin: 0 auto"
            />
          </el-card>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" @click="submitForm">确 定</el-button> -->
          <el-button @click="cancelDetail">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 图表统计弹窗 -->
    <el-dialog
      :title="`${exportDialogTitle} 手环统计数据（请先选择：统计时间范围）`"
      v-model="exportDialogVisible"
      width="90%"
      :style="dialogStyle"
      append-to-body
      :close-on-click-modal="false"
      :before-close="handleExportDialogClose"
      custom-class="custom-dialog"
    >
      <div class="dialog-content" v-loading="chartLoading">
        <el-form :model="queryExportParams" ref="queryRef" :inline="true">
          <!--<el-form-item label="选择时间">
            <el-date-picker
              v-model="queryExportParams.date"
              type="datetimerange"
              range-separator="至"
              value-format="YYYY-MM-DD HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>-->
          <el-form-item label="选择日期">
            <el-date-picker
              v-model="queryExportParams.date"
              type="daterange"
              range-separator="至"
              value-format="YYYY-MM-DD"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <!-- <el-form-item label="分布位置">
          <el-select
            v-model="queryExportParams.field"
            placeholder="请选择分布位置"
            style="width: 150px"
            clearable
            multiple
          >
            <el-option
              v-for="dict in wristband_adv_field"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item> -->
          <el-form-item>
            <el-button
              type="primary"
              icon="Search"
              @click="handleExportDataQuery"
              >搜索</el-button
            >
            <!-- 启用重置按钮 -->
            <el-button icon="Refresh" @click="resetExportQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 用于展示ECharts图表的容器，添加加载状态提示 -->
        <div class="chart-wrapper" :style="chartContainerStyle">
          <div ref="chartRef" :style="chartContainerStyle"></div>
          <div class="chart-actions" v-show="hasChartData">
            <el-button
              type="primary"
              size="small"
              @click="exportChartAsImage('png')"
              icon="Picture"
              >导出PNG</el-button
            >

            <el-button
              type="success"
              size="small"
              @click="exportChartAsImage('jpeg')"
              icon="Picture"
              >导出JPEG</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="exportChartAsHTML"
              icon="Picture"
              >导出html</el-button
            >
          </div>
        </div>
      </div>

      <!-- <div
        v-else
        style="
          width: 100%;
          height: 400px;
          display: flex;
          justify-content: center;
          align-items: center;
        "
      >
        <el-spinner size="large" />
      </div> -->
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" @click="handleExportImg">确 定</el-button> -->
          <el-button @click="handleExportDialogClose">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Post">
import { ref, onMounted, nextTick, onBeforeUnmount } from "vue";
import { debounce } from "lodash";

import echarts from "@/utils/echarts"; // 引入我们创建的按需引入的 echarts
import {
  createOTA,
  getFirmwaresListByType,
  getOtaTaskById,
  deleteOtaTaskById,
  mqttOtaUpgrade,
  getFirmwareProdTask,
  SetFirmwareProdTask,
} from "@/api/system/firmware/ota";
import {
  createFirmwares,
  updateFirmwaresById,
  getFirmwaresList,
} from "@/api/system/user";
import {
  getWristbandList,
  getWristbandAdvByMac,
  getWristbandHistoryByMac,
  wristbandExportImg,
  exportData,
} from "@/api/system/firmware/wb";
import { getClassList } from "@/api/system/school/class";
import { getSchoolList } from "@/api/system/school/school";
import { getEdgroupList } from "@/api/system/school/edgroup";
import { getGatewayList } from "@/api/system/firmware/gateway";
const { proxy } = getCurrentInstance();
const { action_ota, firmware_type, ota_update_mode, wristband_adv_field } =
  proxy.useDict(
    "action_ota",
    "firmware_type",
    "ota_update_mode",
    "wristband_adv_field"
  );
import {
  getCurrentDayDate,
  formartIOSDate,
  formatDate,
} from "@/utils/dateFormart";
import { version } from "nprogress";
const wristbandList = ref([]);
const open = ref(false);
const openHistory = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const wristbandDetail = ref([]);
const schoolList = ref([]);
const EdgroupList = ref([]);
const classList = ref([]);
const exportDialogVisible = ref(false);
const exportDialogTitle = ref("");
const chartLoading = ref(false);
const hasChartData = ref(false);
const chartRef = ref(null);
let chartInstance = null;
const dialogStyle = ref({});
const chartContainerStyle = ref({});

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    fw_name: undefined,
    mac: undefined,
    fw_version: undefined,
    task_id: undefined,
  },
  rules: {},
  queryExportParams: {
    mac: undefined,
    date: [],
    field: [],
    type: undefined,
  },
});
const { queryParams, form, rules, queryExportParams } = toRefs(data);
const dataDetail = reactive({
  loadingDetail: false,
  queryParamsDetail: {
    pageNum: 1,
    pageSize: 256,
    date: [new Date(), new Date(new Date() - 250 * 1000)],
    current_wb: undefined,
    wb_mac: undefined,
    gw_mac: undefined,
    status: false,
  },
  totalDetail: 0,
  refreshTimer: null, // 新增定时器变量
});
const { queryParamsDetail, loadingDetail, totalDetail, refreshTimer } =
  toRefs(dataDetail);
const formatOnlineTime = (time) => {
  if (!time) {
    return " -- ";
  }
  const countTime = formatDate(time);
  return countTime || " -- ";
};
const gatewayList = ref([]);
const ota_update_limit = ref([
  { label: "不限制", value: 0 },
  { label: "开启时间限制", value: 1 },
  { label: "开启数量限制", value: 2 },
]);
// OTA任务
const dataOTA = reactive({
  formOTA: {},
  queryParamsOTA: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    name: undefined,
    status: undefined,
  },
  rulesOTA: {
    firmwareid: [
      { required: true, message: "固件名称不能为空", trigger: "change" },
    ],
    path: [{ required: true, message: "路径不能为空", trigger: "blur" }],
    duration: [
      { required: true, message: "升级时限不能为空", trigger: "blur" },
    ],
    wb_count: [
      { required: true, message: "手环数量不能为空", trigger: "blur" },
    ],
  },
});

const { queryParamsOTA, formOTA, rulesOTA } = toRefs(dataOTA);

// OTA表单重置
function resetOTA() {
  formOTA.value = {
    full: 0,
    path: "/store/firmware/last.bin",
    firmwareid: "", // 固件id
    gw_mac: [], // 网关
    wb_mac: [], // 手环网关
    gw_full: 0,
    wb_full: 0,
    duration: 18000,
    wb_count: undefined,
    updateMode: "updown",
    updateLimit: 0,
    isprod: false,
  };
  ids.value = [];
  console.log("formOTA", formOTA);
  proxy.resetForm("OTARef");
}

const props = defineProps({
  edgroup_id: {
    type: [String, Number],
    required: false, // 因为可能不传入，设为非必填
    default: undefined,
  },
  school_id: {
    type: [String, Number],
    required: false, // 因为可能不传入，设为非必填
    default: undefined,
  },
  class_id: {
    type: [String, Number],
    required: false, // 因为可能不传入，设为非必填
    default: undefined,
  },
});

// 在定义 queryParams 后，将 props 中的值赋给 queryParams
watch(
  () => [props.edgroup_id, props.school_id, props.class_id],
  (
    [newEdgroup, newSchool, newClass],
    [oldEdgroup, oldSchool, oldClass] = []
  ) => {
    let needQuery = false;
    if (newEdgroup !== oldEdgroup) {
      queryParams.value.edgroup_id = newEdgroup || null;
      if (newEdgroup) changeEdgroup();
      needQuery = true;
    }
    if (newSchool !== oldSchool) {
      queryParams.value.school_id = newSchool || null;
      if (newSchool) changeSchool();
      needQuery = true;
    }
    if (newClass !== oldClass) {
      queryParams.value.class_id = newClass || null;
      needQuery = true;
    }
    if (needQuery) {
      getList();
    }
  },
  { immediate: true }
);
const sortTime = (a, b) => {
  return new Date(a.time) - new Date(b.time); // 升序
};
// 定义计算步数颜色的方法
const getStepsColor = (steps) => {
  if (steps && steps > 4500) {
    return "#67c23a";
  } else if (steps && steps > 0) {
    return "inherit";
  } else {
    return "#F56C6C";
  }
};
const getTemperatureColor = (temperature) => {
  if (temperature && temperature > 37.5) {
    return "#F56C6C";
  } else if (temperature && temperature >= 35.5) {
    return "#67c23a";
  } else {
    return "#E6A23C";
  }
};
const firmwaresLists = ref({
  wb: [], // 初始化为空数组
  gw: [],
});
const firmwareLoading = ref(false);
const getRssiColor = (rssi) => {
  if (rssi && rssi > -40) {
    return "#67c23a";
  } else if (rssi && rssi >= -80) {
    return "#E6A23C";
  } else {
    return "#F56C6C";
  }
};
function sortable(arr) {
  const sortedArr = [...arr].sort((a, b) => {
    if (a.time > b.time) return -1;
    if (a.time < b.time) return 1;
    return a.idx - b.idx;
  });
  return sortedArr;
}

/** 取消按钮 */
function cancelOTA() {
  openOTA.value = false;
  resetOTA();
}
// 固件列表
async function getFirmwaresLists() {
  firmwareLoading.value = true;
  try {
    const response = await getFirmwaresListByType();
    if (response.code === 200) {
      firmwaresLists.value = response.data;
      console.log("固件列表----", firmwaresLists.value);
    } else {
      firmwaresLists.value = { wb: [], gw: [] };
      console.error("获取固件列表失败:", response.msg);
    }
  } catch (error) {
    console.error("加载固件时出错:", error);
    firmwaresLists.value = { wb: [], gw: [] };
  } finally {
    firmwareLoading.value = false;
  }
}

/** 查询手环列表 */
function getList() {
  console.log("1111111");
  loading.value = true;
  const now = new Date();
  queryParamsDetail.value.date = [
    new Date(now.getTime() - 250 * 1000 + 8 * 60 * 60 * 1000).toISOString(),
    new Date(now.getTime() + 8 * 60 * 60 * 1000).toISOString(),
  ];
  console.log("查询手环列表参数", queryParams.value);
  getWristbandList(queryParams.value)
    .then((response) => {
      console.log("查询手环列表出参", response.data);
      wristbandList.value = response.data.data;
      total.value = response.data.total;
    })
    .finally(() => {
      loading.value = false;
    });
  getFirmwaresList(queryParams.value).then((response) => {
    console.log("固件列表", response.data.data);
    postList.value = response.data.data;
  });
}
// 提交OTA任务
function submitFormOTA() {
  proxy.$refs["OTARef"].validate((valid) => {
    if (!firmwaresLists.value.wb?.length) {
      proxy.$modal.msgError("固件列表未加载，请重试");
      return;
    }
    if (valid) {
      if (formOTA.value.gw_full != 1 && formOTA.value.gw_mac?.length <= 0) {
        proxy.$modal.msgError("请选择进行升级的网关！");
        return;
      }
      if (formOTA.value.wb_full != 1 && formOTA.value.wb_mac?.length <= 0) {
        proxy.$modal.msgError("请选择要升级的手环！");
        return;
      }
      // 限制手环升级数量 50
      if (formOTA.value.wb_full != 1 && formOTA.value.wb_mac?.length > 50) {
        proxy.$modal.msgError("要升级的手环数量不能超过50个！");
        return;
      }
      const params = {
        ...formOTA.value,
        gw_mac:
          formOTA.value.gw_full != 1 && formOTA.value.gw_mac.length > 0
            ? formOTA.value.gw_mac.join(",")
            : "",
        wb_mac:
          formOTA.value.wb_full != 1 && formOTA.value.wb_mac.length > 0
            ? formOTA.value.wb_mac.join(",")
            : "",
      };
      if (formOTA.value.id != undefined) {
        //   console.log(form.value);
        //   updateFirmwaresById(form.value).then((response) => {
        //     const { code, data, msg } = response;
        //     if (code === 200) {
        //       proxy.$modal.msgSuccess("固件修改成功");
        //       openOTA.value = false;
        //       getList();
        //     } else {
        //       proxy.$modal.msgError("固件修改失败");
        //     }
        //   });
      } else {
        // console.log('创建OTA任务', formOTA.value);
        formOTA.value.dictType = "firmware_type";
        // console.log('提交OTA任务',formOTA.value )
        createOTA({
          ...params,
          dictType: formOTA.value.dictType,
        }).then((response) => {
          // console.log(response);
          const { code, data, msg } = response;
          if (code === 200) {
            console.log("创建成功", data);
            // 创建成功后，弹出是否立即升级
            proxy.$modal
              .confirm(`是否现在升级任务编号为 ${data.id} 的任务？`)
              .then(function () {
                console.log("立即升级");
                openOTA.value = false;
                return mqttOtaUpgrade(data);
              })
              .then(() => {
                console.log("升级成功");
                getList();
                proxy.$modal.msgSuccess("开始升级");
              })
              .catch((err) => {
                console.log("升级失败", err);
              });
          } else {
            proxy.$modal.msgError("OTA任务创建失败");
          }
        });
      }
    }
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
  };
  proxy.resetForm("wristbandRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.mac);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 升级操作 */
function handleUpgrade(row) {
  console.log("升级参数", row);
  // const params = {
  //   gw_mac: row.gw_mac,
  //   taskId: row.id,
  //   firmwareid: row.firmwareid,
  //   localPath: row.path,
  //   force: row.force||false,
  // }
  proxy.$modal
    .confirm(`是否现在升级任务编号为 ${row.id} 的任务？`)
    .then(function () {
      return mqttOtaUpgrade(row);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("开始升级");
    })
    .catch(() => {});
}
const openOTA = ref(false);
// 初始化网关和手环的mac数据
function initGatewayData(params) {
  // 网关列表
  getGatewayList().then((response) => {
    console.log("gw", response.data);
    const { data, msg, code } = response;
    gatewayList.value = code === 200 ? data?.data : [];
  });
}

function gwByClassId(params) {
  // 网关列表
  getGatewayList({ class_id: queryParams.value.class_id }).then((response) => {
    console.log("gw", response.data);
    const { data, msg, code } = response;
    const gwList = code === 200 ? data?.data : [];
    formOTA.value.gw_mac = gwList.map((item) => item.mac);
  });
}
// 创建OTA任务
function creatOTA() {
  getFirmwaresLists();
  // 获取选中的数据
  initGatewayData();
  console.log("选中的数据:", ids.value, wristbandList);
  if (ids.value.length <= 0) {
    proxy.$modal.msgError("请选择要升级的手环！");
    return;
  }
  if (ids.value.length > 50) {
    proxy.$modal.msgError("升级的手环数量不能超过50个！");
    return;
  }
  // 弹出创建任务的对话框
  proxy.$modal
    .confirm(`是否现在创建OTA任务【手环${ids.value.length}】？`)
    .then(function () {
      // resetOTA();
      // wb_mac: ids.value.join(','),
      formOTA.value.wb_mac = ids.value;
      formOTA.value.updateMode = "updown";
      formOTA.value.updateLimit = 0;
      formOTA.value.path = "/store/firmware/last.bin";
      // 获取网关和手环数据
      gwByClassId();
      openOTA.value = true;
      title.value = "创建OTA任务";
    });
}
// 全部OTA(后期用到班级表里面)
function creatAllOTA() {
  getFirmwaresLists();
  initGatewayData();
  // 弹出创建任务的对话框
  proxy.$modal
    .confirm(`是否现在创建OTA任务[手环${wristbandList.value.length}个]？`)
    .then(function () {
      // resetOTA();
      // wb_mac: ids.value.join(','),
      formOTA.value.wb_mac = wristbandList.value.map((item) => item.mac);
      formOTA.value.updateMode = "updown";
      formOTA.value.updateLimit = 0;
      formOTA.value.path = "/store/firmware/last.bin";
      // 获取网关和手环数据
      gwByClassId();
      openOTA.value = true;
      title.value = "创建OTA任务";
    });
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加固件";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getOtaTaskById(id).then((response) => {
    // console.log(response);
    form.value = response.data;
    open.value = true;
    title.value = "修改OTA任务";
  });
}
/** 查看按钮操作 */
function handleView(row) {
  const now = new Date();
  queryParamsDetail.value.wb_mac = row.mac;
  queryParamsDetail.value.current_wb = row;
  queryParamsDetail.value.pageNum = 1;
  queryParamsDetail.value.pageSize = 15;
  queryParamsDetail.value.status = false;
  resetDetail();
  // 先清除之前的定时器
  if (refreshTimer.value) {
    console.log("show 清除定时器");
    clearInterval(refreshTimer.value);
    refreshTimer.value = null;
  }

  // 立即获取一次数据
  getWristbandDetails();

  // 设置定时器，每1秒刷新一次
  // refreshTimer.value = setInterval(() => {
  //   handleQueryDetail();
  // }, 1000);

  open.value = true;
  title.value = "手环详情";
}
function handleHistoryView(row) {
  const now = new Date();
  queryParamsDetail.value.wb_mac = row.mac;
  queryParamsDetail.value.current_wb = row;
  queryParamsDetail.value.pageNum = 1;
  queryParamsDetail.value.pageSize = 15;
  queryParamsDetail.value.status = false;
  resetDetail();
  // 先清除之前的定时器
  if (refreshTimer.value) {
    console.log("show 清除定时器");
    clearInterval(refreshTimer.value);
    refreshTimer.value = null;
  }

  // 立即获取一次数据
  getWristbandHistoryDetails();

  // 设置定时器，每1秒刷新一次
  // refreshTimer.value = setInterval(() => {
  //   handleQueryDetail();
  // }, 1000);

  openHistory.value = true;
  title.value = "手环历史详情";
}

/** 获取手环详情 */
function getWristbandDetails(isRefreshDate) {
  // loading.value = true;
  // loadingDetail.value = true;
  // console.log("获取手环详情入参: ", queryParamsDetail.value);
  const paramsDate = [];
  const now = new Date();
  if (!isRefreshDate) {
    queryParamsDetail.value.date = [
      new Date(now.getTime() - 250 * 1000 + 8 * 60 * 60 * 1000).toISOString(),
      new Date(now.getTime() + 8 * 60 * 60 * 1000).toISOString(),
    ];
  }
  const params = {
    pageNum: queryParamsDetail.value.pageNum,
    pageSize: queryParamsDetail.value.pageSize,
    date: queryParamsDetail.value.date,
    wb_mac: queryParamsDetail.value.wb_mac,
    gw_mac: queryParamsDetail.value.gw_mac,
  };
  getWristbandAdvByMac(params)
    .then(async (response) => {
      console.log("获取手环详情", response.data);
      if (response.code === 200) {
        wristbandDetail.value = response.data.data;
        totalDetail.value = response.data.total;
      } else {
        wristbandDetail.value = [];
        totalDetail.value = 0;
      }
      let result = await sortable(wristbandDetail.value);
      // console.log("result", result);
      // 根据 result 进行统计，在 idx: 0-255 之间，统计一个手环在统计数据中上报了多少条（去重 idx），漏包率是多少
      await getCount(result);
      wristbandDetail.value.forEach((item) => {});
    })
    .finally(() => {
      loadingDetail.value = false;
    });
}
function getWristbandHistoryDetails(isRefreshDate) {
  // loading.value = true;
  // loadingDetail.value = true;
  // console.log("获取手环详情入参: ", queryParamsDetail.value);
  const paramsDate = [];
  const now = new Date();
  if (!isRefreshDate) {
    queryParamsDetail.value.date = [
      new Date(now.getTime() - 250 * 1000 + 8 * 60 * 60 * 1000).toISOString(),
      new Date(now.getTime() + 8 * 60 * 60 * 1000).toISOString(),
    ];
  }
  const params = {
    pageNum: queryParamsDetail.value.pageNum,
    pageSize: queryParamsDetail.value.pageSize,
    date: queryParamsDetail.value.date,
    wb_mac: queryParamsDetail.value.wb_mac,
    gw_mac: queryParamsDetail.value.gw_mac,
  };
  getWristbandHistoryByMac(params)
    .then(async (response) => {
      console.log("获取手环详情", response.data);
      if (response.code === 200) {
        wristbandDetail.value = response.data.data;
        totalDetail.value = response.data.total;
      } else {
        wristbandDetail.value = [];
        totalDetail.value = 0;
      }
      let result = await sortable(wristbandDetail.value);
      // console.log("result", result);
      // 根据 result 进行统计，在 idx: 0-255 之间，统计一个手环在统计数据中上报了多少条（去重 idx），漏包率是多少
      await getCount(result);
      wristbandDetail.value.forEach((item) => {});
    })
    .finally(() => {
      loadingDetail.value = false;
    });
}

const last_idx = ref();
const new_idx = ref();
const pack_count = ref();
const true_pack_count = ref();
const lost_pack_count = ref();
const lost_pack_percent = ref();
// 统计
function getCount(result) {
  // result = result.slice(50, 545);
  //   console.log("result", result);
  if (result && result.length > 0) {
    // 1. 提取所有idx并按时间排序（假设result已按时间排序）
    const idxList = result
      .map((item) => item.idx)
      .filter((idx) => idx >= 0 && idx <= 255);

    if (idxList.length === 0) {
      console.log("无有效idx数据");
      return;
    }

    // 2. 获取最旧和最新的idx
    last_idx.value = idxList[idxList.length - 1];
    new_idx.value = idxList[0];

    // 3. 计算理论应接收的包数
    if (new_idx.value >= last_idx.value) {
      // 正常情况：200 -> 255
      pack_count.value = new_idx.value - last_idx.value + 1;
    } else {
      // 循环情况：255 -> 34
      pack_count.value = 255 - last_idx.value + 1 + (new_idx.value + 1);
    }

    // 4. 统计实际接收的唯一包数 唯一索引集合
    const unique_set = new Set(idxList);
    // console.log("唯一索引集合", unique_set);
    true_pack_count.value = unique_set.size;

    // 5. 计算丢包率
    lost_pack_count.value = pack_count.value - true_pack_count.value;
    lost_pack_percent.value = (
      (lost_pack_count.value / pack_count.value) *
      100
    ).toFixed(2);

    // 6. 打印结果
    // console.log("【统计结果】");
    // console.log(`- 最旧idx: ${last_idx.value}, 最新idx: ${new_idx.value}`);
    // console.log(`- 理论应接收包数: ${pack_count.value}个`);
    // console.log(`- 实际接收包数（去重）: ${true_pack_count.value}个`);
    // console.log(`- 丢失包数: ${lost_pack_count.value}个`);
    // console.log(`- 丢包率: ${lost_pack_percent.value}%`);

    // 可选：列出缺失的idx（如果数量合理）
    if (lost_pack_count.value > 0 && lost_pack_count.value <= 50) {
      const lost_set = [];
      if (new_idx.value >= last_idx.value) {
        for (let i = last_idx.value; i <= new_idx.value; i++) {
          if (!unique_set.has(i)) lost_set.push(i);
        }
      } else {
        for (let i = last_idx.value; i <= 255; i++) {
          if (!unique_set.has(i)) lost_set.push(i);
        }
        for (let i = 0; i <= new_idx; i++) {
          if (!unique_set.has(i)) lost_set.push(i);
        }
      }
      //  console.log("- 缺失的索引:", lost_set);
    }
  } else {
    // console.log("无有效数据可供分析");
  }
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["wristbandRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        // console.log(form.value);
        updateFirmwaresById(form.value).then((response) => {
          const { code, data, msg } = response;
          if (code === 200) {
            proxy.$modal.msgSuccess("手环修改成功");
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError("手环修改失败");
          }
        });
      } else {
        // console.log(form.value);
        createFirmwares(form.value).then((response) => {
          // console.log(response);
          const { code, data, msg } = response;
          if (code === 200) {
            proxy.$modal.msgSuccess("手环新增成功");
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError("手环新增失败");
          }
        });
      }
    }
  });
}
const postList = ref([]);
// OTA任务选择固件 带出固件类型
function firmwareChange(el, value) {
  const selectedFirmware = firmwaresLists.value[el].find(
    (dict) => dict.id === value
  );
  console.log("OTA任务选择固件: ", selectedFirmware);
  formOTA.value.isprod = selectedFirmware?.isprod == "true" ? true : false;
  // formOTA.value.firmwareType = selectedFirmware.firmwareType; //value.firmwareType
  // formOTA.value.version = selectedFirmware.version;
  formOTA.value.full = 0;
  // formOTA.value.force = false;
  // formOTA.value.remain = false;
  formOTA.value.duration = undefined;
  formOTA.value.wb_count = undefined;

  // console.log('OTA任务选择固件', form.value)
}
/** 详情close按钮 */
function handleClose() {
  // 清除定时器
  if (refreshTimer.value) {
    console.log("close 清除定时器");
    clearInterval(refreshTimer.value);
    refreshTimer.value = null;
    queryParamsDetail.value.status = false;
  }
  open.value = false;
  openHistory.value = false;
  resetDetail();
}
/** 详情取消按钮 */
function cancelDetail() {
  // 清除定时器
  if (refreshTimer.value) {
    console.log("cancel 清除定时器");
    clearInterval(refreshTimer.value);
    refreshTimer.value = null;
    queryParamsDetail.value.status = false;
  }
  open.value = false;
  resetDetail();
}

/** 详情表单重置 */
function resetDetail() {
  // proxy.resetForm("wristbandRef");
}

/** 详情搜索按钮操作 */
function handleQueryDetail() {
  queryParamsDetail.value.pageNum = 1;
  getWristbandDetails(true);
}
function handleQueryHistoryDetail() {
  queryParamsDetail.value.pageNum = 1;
  getWristbandHistoryDetails(true);
}
/** 详情重置按钮操作 */
function resetQueryDetail() {
  // dateRange.value = [];
  proxy.resetForm("queryDetailRef");
  handleQueryDetail();
}
function resetQueryHistoryDetail() {
  // dateRange.value = [];
  proxy.resetForm("queryDetailHistoryRef");
  handleQueryHistoryDetail();
}
/** 详情开始暂停按钮操作 */
function timedQueryDetail() {
  if (queryParamsDetail.value.status) {
    console.log("暂停 清除定时器");
    clearInterval(refreshTimer.value);
    queryParamsDetail.value.status = false;
    return;
  } else {
    // 先清除之前的定时器
    if (refreshTimer.value) {
      console.log("show 清除定时器");
      clearInterval(refreshTimer.value);
      refreshTimer.value = null;
    }
    // 立即获取一次数据
    getWristbandDetails();
    queryParamsDetail.value.status = true;
    // 设置定时器，每1秒刷新一次
    refreshTimer.value = setInterval(() => {
      getWristbandDetails();
    }, 1000);
    queryParamsDetail.value.status = true;
  }
  // queryParamsDetail.value.status = !queryParamsDetail.value.status
}
/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除编号为"' + ids + '"的数据项？')
    .then(function () {
      return deleteOtaTaskById(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "wristband/export",
    {
      // ...queryParams.value
    },
    `wristband_mac_${new Date().getTime()}.xlsx`
  );
}
function handleExportWB(data, timeRange) {
  if (!timeRange || !data?.mac) {
    proxy.$modal.msgError("请先选择手环");
    return;
  }
  proxy.download(
    `wristband_adv/export?timeRange=${timeRange}&mac=${data?.mac}`,
    {
      // ...params,
    },
    `wristband_adv_${new Date().getTime()}.xlsx`
  );
}
function resetExportQuery() {
  // 假设 queryExportParams 是响应式对象中的导出查询参数
  queryExportParams.value = {
    mac: undefined,
    date: [],
    field: [],
    type: undefined,
  };
  // 可根据需求添加其他重置逻辑，例如重新查询数据
  handleExportDataQuery();
}
function handleExportDataQuery() {
  chartLoading.value = true;
  let startTimeData = null;
  let endTimeData = null;
  switch (queryExportParams.value.type) {
    case "1d":
      startTimeData = queryExportParams.value.date[0];
      endTimeData = queryExportParams.value.date[1];
      break;
    case "5m":
      startTimeData =
        queryParamsDetail.value.date.length > 0
          ? queryParamsDetail.value.date[0]
          : new Date(
              now.getTime() - 250 * 1000 + 8 * 60 * 60 * 1000
            ).toISOString();
      endTimeData =
        queryParamsDetail.value.date.length > 0
          ? queryParamsDetail.value.date[1]
          : new Date(now.getTime() + 8 * 60 * 60 * 1000).toISOString();
      break;
    default:
      startTimeData = new Date(
        now.getTime() - 250 * 1000 + 8 * 60 * 60 * 1000
      ).toISOString();
      endTimeData = new Date(now.getTime() + 8 * 60 * 60 * 1000).toISOString();
      break;
  }
  const params = {
    mac: queryExportParams.value.mac,
    field: queryExportParams.value.field,
    //startTime: startTimeData, //"2025-06-01T00:00:00Z",
    //endTime: endTimeData, //"2025-06-18T23:59:59Z"
    startTime: "2025-06-20T08:00:00Z",
    endTime: "2025-06-20T20:00:00Z",
  };
  console.log("手环图表统计 入参", JSON.stringify(params));
  exportData(params)
    .then((response) => {
      const { code, data, msg } = response;
      console.log("手环图表统计 出参", response);
      if (code === 200) {
        const res_data = data.data;
        // res_data 数组内容包括：时间、步数、心率、温度、运动强度、充电状态、佩戴状态、运动方差、是否需要授时、心率置信度、电量、心率变异
        // 定义一个对象，用于存储不同时间的数据
        const timeData = {};
        // 遍历 res_data 数组，将数据按照时间分组
        res_data.forEach((item) => {
          const time = item.time;
          if (!timeData[time]) {
            timeData[time] = [];
          }
          timeData[time].push(item);
        });
        // 定义一个数组，用于存储最终的图表数据
        const chartDataFinal = [];
        // 遍历 timeData 对象，将数据转换为图表需要的格式
        for (const time in timeData) {
          const data = timeData[time];
          // 计算步数的平均值
          const stepsAvg =
            data.reduce((sum, item) => sum + item.steps, 0) / data.length;
          // 计算心率的平均值
          const heartRateAvg =
            data.reduce((sum, item) => sum + item.hr, 0) / data.length;
          // 计算温度的平均值
          const temperatureAvg =
            data.reduce((sum, item) => sum + item.temperature, 0) / data.length;
          // 计算运动强度的平均值
          const intensityAvg =
            data.length > 0
              ? data.reduce(
                  (sum, item) => sum + (Number(item.motion) || 0),
                  0
                ) / data.length
              : 0;
          // 计算充电状态的平均值
          const chargeStatusAvg =
            data.reduce((sum, item) => sum + Number(item.charging), 0) /
            data.length;
          // 计算佩戴状态的平均值
          const wearingStatusAvg =
            data.reduce((sum, item) => sum + Number(item.wear_on), 0) /
            data.length;
          // 计算运动方差的平均值，保留6位小数，且转为数字类型
          const varianceAvg =
            data.length > 0
              ? Number(
                  (
                    data.reduce(
                      (sum, item) => sum + (Number(item.motion_variance) || 0),
                      0
                    ) / data.length
                  ).toFixed(6)
                )
              : 0;
          // 计算是否需要授时的平均值
          const needSyncAvg =
            data.reduce((sum, item) => sum + Number(item.req_rt), 0) /
            data.length;
          // 计算心率置信度的平均值
          const heartRateConfidenceAvg =
            data.reduce((sum, item) => sum + (item.hr_confidence || 0), 0) /
            data.length;
          // 计算电量的平均值
          const batteryAvg =
            data.reduce((sum, item) => sum + item.bat_vol, 0) / data.length;
          // 计算心率变异的平均值
          const heartRateVarianceAvg =
            data.reduce((sum, item) => sum + item.hrv, 0) / data.length;
          // 将计算得到的平均值添加到 chartDataFinal 数组中
          chartDataFinal.push({
            time: time, // 时间
            stepsAvg: stepsAvg, // 步数
            heartRateAvg: heartRateAvg, // 心率
            temperatureAvg: temperatureAvg, // 温度
            intensityAvg: Number(intensityAvg) || 0,
            varianceAvg: Number(varianceAvg) || 0,
            chargeStatusAvg: chargeStatusAvg, // 充电状态
            wearingStatusAvg: wearingStatusAvg, // 佩戴状态
            needSyncAvg: needSyncAvg, // 是否授时
            heartRateConfidenceAvg: heartRateConfidenceAvg, // 心率置信度
            batteryAvg: batteryAvg, // 电量
            heartRateVarianceAvg: heartRateVarianceAvg, // 心率变异
          });
        }
        // 输出最终的图表数据
        console.log(chartDataFinal);
        // 定义一个数组，用于存储最终的图表数据
        const chartData = [];
        // 遍历 chartDataFinal 数组，将数据转换为图表需要的格式
        for (const item of chartDataFinal) {
          // 假设这里将时间字符串作为 timeString，时间戳可以根据时间字符串转换
          item.timeString = item.time;
          item.timestamp = new Date(item.time).getTime();
          // 遍历 item 对象，将值为 null 的属性删除
          for (const key in item) {
            if (item[key] === null) {
              delete item[key];
            }
          }
          // 将 item 对象添加到 chartData 数组中
          chartData.push(item);
        }
        // 检查 echarts 是否已经定义
        if (typeof echarts === "undefined") {
          console.error("ECharts 未定义，请确保已经正确引入 ECharts 库。");
          proxy.$modal.msgError("ECharts 未定义，请联系管理员。");
          return;
        }
        function toBeijingTimeString(utcStr) {
          const utcDate = new Date(utcStr);
          // 手动减8小时（8 * 60 * 60 * 1000 毫秒）
          const beijingTime = new Date(utcDate.getTime() - 8 * 3600 * 1000);
          return beijingTime.toLocaleString();
        }

        const startTimeStr = toBeijingTimeString(
          queryExportParams.value.date[0]
        );
        const endTimeStr = toBeijingTimeString(queryExportParams.value.date[1]);

        const titleText = `${exportDialogTitle.value} 手环统计数据（${startTimeStr} ~ ${endTimeStr}）`;
        nextTick(() => {
          if (!chartRef.value) {
            console.error("图表容器未找到");
            return;
          }

          // 如果已有图表实例，先销毁
          if (chartInstance) {
            chartInstance.dispose();
            window.removeEventListener("resize", resizeChart);
          }
          chartInstance = echarts.init(chartRef.value);
          // 准备Y轴配置
          // 优化思路：减少左侧y轴的偏移量，将部分指标合并到右侧y轴，同时调整系列配置中的yAxisIndex
          const colorPalette = [
            "#5470C6",
            "#8AFF33",
            "#A0A0A0",
            "#FAC858",
            "#73C0DE",
            "#3BA272",
            "#FF338A",
            "#9A60B4",
            "#f3b5de",
            "#1E90FF",
            "#FF4500",
          ];

          const seriesConfigs = [
            {
              name: "是否充电",
              yAxisIndex: 0,
              type: "line",
              symbol: "circle",
              lineStyle: { color: colorPalette[0], width: 2 },
              itemStyle: { color: colorPalette[0] },
              data: chartData.map((d) => (d.chargeStatusAvg ? 0.2 : -0.1)),
            },
            {
              name: "是否佩戴",
              yAxisIndex: 0,
              type: "line",
              symbol: "circle",
              lineStyle: { color: colorPalette[1], width: 2 },
              itemStyle: { color: colorPalette[1] },
              data: chartData.map((d) => (d.wearingStatusAvg ? 0.5 : -0.1)),
            },
            {
              name: "是否授时",
              yAxisIndex: 0,
              type: "line",
              symbol: "circle",
              lineStyle: { color: colorPalette[2], width: 2 },
              itemStyle: { color: colorPalette[2] },
              data: chartData.map((d) => (d.needSyncAvg ? 0.8 : -0.1)),
            },
            {
              name: "步数",
              yAxisIndex: 1,
              type: "line",
              symbol: "circle",
              lineStyle: { color: colorPalette[3], width: 2 },
              itemStyle: { color: colorPalette[3] },
              data: chartData.map((d) => d.stepsAvg),
            },
            {
              name: "心率",
              yAxisIndex: 2,
              type: "line",
              symbol: "circle",
              lineStyle: { color: colorPalette[4], width: 2 },
              itemStyle: { color: colorPalette[4] },
              data: chartData.map((d) => d.heartRateAvg),
            },
            {
              name: "温度",
              yAxisIndex: 3,
              type: "line",
              symbol: "circle",
              lineStyle: { color: colorPalette[5], width: 2 },
              itemStyle: { color: colorPalette[5] },
              data: chartData.map((d) => d.temperatureAvg),
            },
            {
              name: "运动强度",
              yAxisIndex: 4,
              type: "line",
              symbol: "circle",
              lineStyle: { color: colorPalette[6], width: 2 },
              itemStyle: { color: colorPalette[6] },
              data: chartData.map((d) => Number(d.intensityAvg) || 0),
            },
            {
              name: "运动方差",
              yAxisIndex: 5,
              type: "line",
              symbol: "circle",
              lineStyle: { color: colorPalette[7], width: 2 },
              itemStyle: { color: colorPalette[7] },
              data: chartData.map((d) => Number(d.varianceAvg) || 0),
            },
            {
              name: "心率置信度",
              yAxisIndex: 6,
              type: "line",
              symbol: "circle",
              lineStyle: { color: colorPalette[8], width: 2 },
              itemStyle: { color: colorPalette[8] },
              data: chartData.map((d) => d.heartRateConfidenceAvg || 0),
            },
            {
              name: "电量",
              yAxisIndex: 7,
              type: "line",
              symbol: "circle",
              lineStyle: { color: colorPalette[9], width: 2 },
              itemStyle: { color: colorPalette[9] },
              data: chartData.map((d) => d.batteryAvg),
            },
            {
              name: "心率变异",
              yAxisIndex: 8,
              type: "line",
              symbol: "circle",
              lineStyle: { color: colorPalette[10], width: 2 },
              itemStyle: { color: colorPalette[10] },
              data: chartData.map((d) => d.heartRateVarianceAvg),
            },
          ];

          const yAxisConfigs = [
            {
              type: "value",
              name: "",
              min: -0.2,
              max: 1.2,
              interval: 0.1,
              axisLine: {
                lineStyle: {
                  color: "#999", // 中性灰
                },
              },
              axisLabel: {
                color: "#999",
                fontWeight: "bold",
                formatter: (val) => {
                  if (val === -0.1) return "否";
                  if (val === 0.2) return "已充电";
                  if (val == 0.5) return "已佩戴";
                  if (val === 0.8) return "已授时";
                  return "";
                },
              },
            },
            {
              type: "value",
              name: "步数（步）",
              axisLine: {
                lineStyle: { color: colorPalette[4] }, // 第三个颜色
              },
              position: "left",
              offset: 60,
            },
            {
              type: "value",
              name: "心率（次/分钟）",
              axisLine: {
                lineStyle: { color: colorPalette[5] },
              },
              position: "left",
              offset: 120,
            },
            {
              type: "value",
              name: "温度(℃)",
              axisLine: {
                lineStyle: { color: colorPalette[6] },
              },
              position: "left",
              offset: 180,
            },
            {
              type: "value",
              name: "运动强度",
              axisLine: {
                lineStyle: { color: colorPalette[7] },
              },
              position: "left",
              offset: 240,
            },
            {
              type: "value",
              name: "运动方差",
              axisLine: {
                lineStyle: { color: colorPalette[7] },
              },
              position: "left",
              offset: 300,
            },
            {
              type: "value",
              name: "置信度",
              axisLine: {
                lineStyle: { color: colorPalette[8] },
              },
              position: "left",
              offset: 360,
            },
            {
              type: "value",
              name: "电量（%）",
              max: 100, // 这里设置最大值为100
              axisLine: {
                lineStyle: { color: colorPalette[9] },
              },
              position: "left",
              offset: 420,
            },
            {
              type: "value",
              name: "心率变异",
              axisLine: {
                lineStyle: { color: colorPalette[10] },
              },
              position: "left",
              offset: 480,
            },
          ];

          const legendData = seriesConfigs.map((s) => ({
            name: s.name,
            icon: "circle",
            itemStyle: { color: s.lineStyle.color },
          }));

          const option = {
            title: {
              text: titleText,
              left: "center",
              textStyle: {
                fontSize: 16,
                fontWeight: "bold",
                color: "#333",
              },
            },
            // toolbox: {
            //   feature: {
            //     saveAsImage: {
            //       type: "svg",
            //       name: "chart",
            //     },
            //   },
            // },
            color: colorPalette,
            tooltip: {
              trigger: "axis",
              formatter: function (params) {
                let result = params[0]?.axisValueLabel + "<br/>";
                params.forEach((item) => {
                  const name = item.seriesName;
                  let value = item.data;

                  // 对状态字段做数值转文字处理
                  if (
                    name === "是否充电" ||
                    name === "是否佩戴" ||
                    name === "是否授时"
                  ) {
                    value = value === -0.1 ? "否" : "是";
                  } else if (value === null || value === undefined) {
                    value = "无";
                  }

                  // 添加颜色圆点和显示内容
                  result += `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:${item.color};"></span>`;
                  result += `${name}：${value}<br/>`;
                });
                return result;
              },
            },
            legend: {
              data: legendData,
              type: "scroll",
              top: "top",
              padding: [50, 50],
              textStyle: { color: "#333", fontWeight: "bold" },
              itemGap: 10,
              itemWidth: 10,
              itemHeight: 10,
            },
            grid: {
              left: "320",
              right: "3%",
              bottom: "50px",
              top: "100px",
              containLabel: true,
            },
            xAxis: {
              type: "category",
              boundaryGap: false,
              data: chartData.map((d) => d.time),
              axisLabel: {
                rotate: 30,
                formatter: function (value) {
                  const date = new Date(value);
                  const hours = String(date.getHours()).padStart(2, "0");
                  const minutes = String(date.getMinutes()).padStart(2, "0");
                  const seconds = String(date.getSeconds()).padStart(2, "0");
                  return `${hours}:${minutes}:${seconds}`;
                },
              },
            },
            yAxis: yAxisConfigs.map((axis, index) => {
              // 修正：每个yAxis的颜色与seriesConfigs的yAxisIndex一一对应
              // colorPalette: 0-2为状态，3-10为数据
              let axisColor = "#999";
              if (index === 0) {
                axisColor = "#999";
              } else if (index >= 1 && index <= 8) {
                axisColor = colorPalette[index + 2];
              }
              return {
                ...axis,
                axisLine: {
                  show: true,
                  lineStyle: {
                    color: axisColor,
                    width: 2,
                  },
                },
                axisLabel: {
                  ...axis.axisLabel,
                  color: axisColor,
                  fontWeight: "bold",
                },
                axisTick: {
                  lineStyle: {
                    color: axisColor,
                  },
                },
                splitLine:
                  index === 0
                    ? {
                        show: true,
                        lineStyle: { color: "#eee", type: "dashed" },
                      }
                    : { show: false },
                nameLocation: "middle",
                nameGap: 40,
              };
            }),
            series: seriesConfigs,
            dataZoom: [
              {
                type: "inside",
                start: 0,
                end: 100,
                xAxisIndex: [0],
              },
              {
                type: "slider",
                start: 0,
                end: 100,
                xAxisIndex: [0],
                bottom: 15,
                height: 20,
              },
            ],
          };

          // 使用刚指定的配置项和数据显示图表。
          chartInstance.setOption(option);
          hasChartData.value = true;
          // 初始渲染后立即resize
          setTimeout(() => {
            chartInstance.resize();
          }, 0);
          // 添加resize监听
          window.addEventListener("resize", resizeChart);
        });
      } else {
        proxy.$modal.msgError("导出统计失败");
        hasChartData.value = false;
      }
    })
    .finally(() => {
      chartLoading.value = false;
    });
}

function showExportDialog(data, type) {
  if (!data?.mac) {
    proxy.$modal.msgError("请先选择手环");
    return;
  }
  queryExportParams.value.mac = data?.mac;
  queryExportParams.value.type = type; // 1d 5m
  const u_name =
    data?.student_wristband?.student?.name.length > 2
      ? data?.student_wristband?.student?.name[0] +
        "*" +
        data?.student_wristband?.student?.name.slice(-1)
      : data?.student_wristband?.student?.name[0] + "*";
  exportDialogTitle.value = `${data?.mac} ${u_name ? u_name : ""}  ${
    data?.fw_name ? data?.fw_name : ""
  }`;
  exportDialogVisible.value = true;
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");

  // 早8点
  const start = new Date(`${year}-${month}-${day}T00:00:00.000Z`);
  start.setHours(start.getHours() + 8); // 东八区早8点

  // 晚8点
  const end = new Date(`${year}-${month}-${day}T12:00:00.000Z`);
  end.setHours(end.getHours() + 8); // 东八区晚8点

  const startISO = start.toISOString();
  const endISO = end.toISOString();

  console.log(startISO, endISO);

  queryExportParams.value.date = [startISO, endISO];
}
function handleExportDialogClose() {
  exportDialogVisible.value = false;
  queryExportParams.value.date = [];
  queryExportParams.value.field = [];
  queryExportParams.value.mac = undefined;
  queryExportParams.value.type = undefined;
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  window.removeEventListener("resize", () => {
    chartInstance?.resize();
  });
}
function exportChartAsHTML() {
  if (!chartInstance) {
    proxy.$modal.msgError("图表未加载完成，无法导出");
    return;
  }

  // 获取当前图表配置
  let option = chartInstance.getOption();

  // 手动补充 formatter 函数
  // 1. tooltip
  option.tooltip.formatter = function (params) {
    let result = params[0]?.axisValueLabel + "<br/>";
    params.forEach((item) => {
      const name = item.seriesName;
      let value = item.data;
      if (
        name === "是否充电" ||
        name === "是否佩戴" ||
        name === "是否授时"
      ) {
        value = value === -0.1 ? "否" : "是";
      } else if (value === null || value === undefined) {
        value = "无";
      }
      result += `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:${item.color};"></span>`;
      result += `${name}：${value}<br/>`;
    });
    return result;
  };
  // 2. yAxis[0].axisLabel.formatter
  if (option.yAxis && option.yAxis[0] && typeof option.yAxis[0] === "object") {
    option.yAxis[0].axisLabel.formatter = function (val) {
      if (val === -0.1) return "否";
      if (val === 0.2) return "已充电";
      if (val == 0.5) return "已佩戴";
      if (val === 0.8) return "已授时";
      return "";
    };
  }

  // 3. 重新生成 HTML
  const htmlContent = [
    "<!DOCTYPE html>",
    "<html>",
    "<head>",
    '  <meta charset="UTF-8">',
    "  <title>ECharts 导出图表</title>",
    "  <!-- 引入 ECharts -->",
    '  <script src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"><\/script>',
    "  <style>",
    "    html, body, #chart {",
    "      width: 100%;",
    "      height: 100%;",
    "      margin: 0;",
    "      padding: 0;",
    "    }",
    "  </style>",
    "</head>",
    "<body>",
    '  <div id="chart"></div>',
    "  <script>",
    "    var chart = echarts.init(document.getElementById('chart'));",
    "    var option = " + JSON.stringify(option, function(key, value) {
      // 对函数转为字符串
      if (typeof value === 'function') {
        return value.toString();
      }
      return value;
    }, 2) + ";",
    "    function reviveFunctions(obj) {",
    "      for (var key in obj) {",
    "        if (typeof obj[key] === 'object' && obj[key] !== null) {",
    "          reviveFunctions(obj[key]);",
    "        } else if (typeof obj[key] === 'string' && obj[key].indexOf('function') === 0) {",
    "          obj[key] = eval('(' + obj[key] + ')');",
    "        }",
    "      }",
    "    }",
    "    reviveFunctions(option);",
    "    chart.setOption(option);",
    "  <\/script>",
    "</body>",
    "</html>",
  ].join("\n");

  // 创建下载链接并点击下载
  const blob = new Blob([htmlContent], { type: "text/html" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `echarts_export_${Date.now()}.html`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

function handleExportImg() {
  let startTimeData = null;
  let endTimeData = null;
  switch (queryExportParams.value.type) {
    case "1d":
      startTimeData = queryExportParams.value.date[0];
      endTimeData = queryExportParams.value.date[1];
      break;
    case "5m":
      startTimeData =
        queryParamsDetail.value.date.length > 0
          ? queryParamsDetail.value.date[0]
          : new Date(
              now.getTime() - 250 * 1000 + 8 * 60 * 60 * 1000
            ).toISOString();
      endTimeData =
        queryParamsDetail.value.date.length > 0
          ? queryParamsDetail.value.date[1]
          : new Date(now.getTime() + 8 * 60 * 60 * 1000).toISOString();
      break;
    default:
      startTimeData = new Date(
        now.getTime() - 250 * 1000 + 8 * 60 * 60 * 1000
      ).toISOString();
      endTimeData = new Date(now.getTime() + 8 * 60 * 60 * 1000).toISOString();
      break;
  }
  const params = {
    mac: queryExportParams.value.mac,
    field: queryExportParams.value.field,
    startTime: startTimeData, //"2025-06-01T00:00:00Z",
    endTime: endTimeData, //"2025-06-18T23:59:59Z"
  };
  console.log("导出统计手环 入参", JSON.stringify(params));
  wristbandExportImg(params).then((response) => {
    const { code, data, msg } = response;
    console.log("导出统计手环 出参", response);
    if (code === 200) {
      const res_data = data.data;
      // 下载SVG图片
      // const link = document.createElement('a');
      // link.href = data.data;
      // link.download = '手环统计.svg'; // 可自定义文件名
      // document.body.appendChild(link);
      // link.click();
      // document.body.removeChild(link);
      // data 是 SVG 字符串内容
      let svgContent = res_data;
      // 如果 data 是 URL，先 fetch 内容
      if (res_data.startsWith("http")) {
        fetch(res_data)
          .then((res) => res.text())
          .then((svgText) => downloadSvg(svgText));
      } else if (res_data.startsWith("<svg")) {
        downloadSvg(svgContent);
      } else if (res_data.startsWith("data:image/svg+xml")) {
        // data URL，提取内容
        const svgText = decodeURIComponent(res_data.split(",")[1]);
        downloadSvg(svgText);
      } else {
        proxy.$modal.msgError("导出内容格式不支持");
      }

      proxy.$modal.msgSuccess("导出统计成功");
      exportDialogVisible.value = false;
      handleExportDialogClose();
    } else {
      proxy.$modal.msgError("导出统计失败");
    }
  });
}
function downloadSvg(svgText) {
  const blob = new Blob([svgText], { type: "image/svg+xml" });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = "wristband_chart.svg";
  if (document.body) {
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } else {
    window.open(url); // 兜底方案
  }
  URL.revokeObjectURL(url);
}
/** 重置固件ID选择 */
function resetFirmwareIds() {
  formOTA.value.firmwareid = undefined;
  formOTA.value.updateLimit = 0;
  formOTA.value.duration = undefined;
  formOTA.value.wb_count = undefined;
  formOTA.value.wb_mac = [];
  formOTA.value.wb_full = 0;
  formOTA.value.gw_mac = [];
  formOTA.value.gw_full = 0;
  formOTA.value.path = "/store/firmware/last.bin";
  formOTA.value.updateMode = "updown";
  formOTA.value.remain = false;
  formOTA.value.isprod = false;
}
// 切换教育集团
function changeEdgroup() {
  queryParams.value.school_id = null;
  schoolList.value = [];
  let params = {
    id: queryParams.value.edgroup_id,
  };
  getSchoolList(params).then((res) => {
    schoolList.value = res.data.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
        photo: item.photo,
      };
    });
  });
}
// 切换学校
function changeSchool() {
  queryParams.value.class_id = null;
  classList.value = [];
  let params = {
    school_id: queryParams.value.school_id,
  };
  // console.log('params', params)
  getClassList(params).then((res) => {
    // console.log("班级列表", res.data.data);
    classList.value = res.data.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
        photo: item.photo,
      };
    });
  });
}

function initData() {
  getEdgroupList().then((res) => {
    EdgroupList.value = res.data.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
        photo: item.photo,
      };
    });
  });
  getSchoolList().then((res) => {
    schoolList.value = res.data.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
        photo: item.photo,
      };
    });
  });
  getClassList().then((res) => {
    classList.value = res.data.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
        photo: item.photo,
      };
    });
  });
  getList();
}
// 修改3: 提取resize函数
const resizeChart = () => {
  chartInstance?.resize();
};
// 计算对话框高度
const calculateDialogHeight = () => {
  const windowHeight = window.innerHeight;
  const isMobile = window.innerWidth < 768;
  const height = isMobile
    ? windowHeight * 0.9
    : Math.max(windowHeight * 0.9, 700);
  dialogStyle.value = {
    height: `${height}px`,
    "max-height": "none",
  };

  // 图表容器样式
  const chartHeight = height - 230; // 减去表单和底部按钮高度
  chartContainerStyle.value = {
    width: "100%",
    height: `${Math.max(chartHeight, 400)}px`, // 最小高度400px
    minWidth: "100%",
  };
};
// 导出图表为图片
const exportChartAsImage = (type) => {
  if (!chartInstance) {
    proxy.$modal.msgError("图表未初始化，无法导出");
    return;
  }

  const url = chartInstance.getDataURL({
    type: type,
    pixelRatio: 2, // 提高导出图片质量
    backgroundColor: "#fff",
    excludeComponents: ["toolbox"], // 排除不需要导出的组件
  });

  const link = document.createElement("a");
  link.href = url;
  const randomNum = Math.floor(1000000000 + Math.random() * 9000000000);
  link.download = `图表统计_${new Date().toLocaleString()}_${randomNum}.${type}`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

onMounted(() => {
  calculateDialogHeight();
  window.addEventListener("resize", debounce(calculateDialogHeight, 200));
});

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
    window.removeEventListener("resize", resizeChart);
  }
  window.removeEventListener("resize", calculateDialogHeight);
});
initData();
</script>
<style lang="scss" scoped>
.list-group-top-none .list-group-striped > .list-group-item {
  border-top: none;
}
.wristbandDetail {
  :deep(.pagination-container .el-pagination) {
    right: 20px;
  }
}
.custom-dialog {
  display: flex;
  flex-direction: column;
  max-height: none !important;
  transition: height 0.3s ease;

  .el-dialog__body {
    flex: 1;
    overflow: auto;
    padding: 20px;
    display: flex;
    flex-direction: column;
  }

  .el-dialog__header {
    padding: 20px 20px 10px;
  }
}

.dialog-content {
  flex: 1;
  display: flex;
  flex-direction: column;

  .el-form {
    margin-bottom: 20px;
  }
}

.chart-container {
  flex: 1;
  min-height: 400px;
  transition: height 0.3s ease;
}

.chart-wrapper {
  position: relative;
  width: 100%;

  .chart-actions {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 10;
    display: flex;
    gap: 8px;

    .el-button {
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
  }
}
.dialog-footer {
  padding: 10px 20px 10px;
  text-align: right;
  border-top: 1px solid #ebeef5;
}
</style>
